#include "BluetoothSerial.h"
#include <ESP32Servo.h>
#if !defined(CONFIG_BT_ENABLED) || !defined(CONFIG_BLUEDROID_ENABLED)
#error Bluetooth is not enabled! Please run `make menuconfig` to and enable it
#endif

BluetoothSerial SerialBT;
Servo servo1;
static const int servoPin = 13;
static const int OpenParameter = 100;   //开启开关舵机的角度
static const int CloseParameter = 15; //关闭开关舵机的角度
static const int ResetParemeter = 58; //舵机复位角度

String readMsg = "";
int dutyCycle = 0;
//int position1 = 0;

/* Setting PWM properties */
const int PWMFreq = 50;
const int PWMChannel = 0;
const int PWMResolution = 8;
const int MAX_DUTY_CYCLE = (int)(pow(2, PWMResolution) - 1);
void setup()
{
  Serial.begin(115200);
  ledcSetup(PWMChannel, PWMFreq, PWMResolution);
  ledcAttachPin(servoPin, PWMChannel);
  ledcWrite(PWMChannel, dutyCycle);
  SerialBT.begin("ESP32BLE_Servo"); //蓝牙设备名称
  delay(50);
  Serial.println("The device started, now you can pair it with bluetooth!");

}
/*
   蓝牙串口接收
*/
void ReceiverBleMessage()
{
  while (SerialBT.available() > 0)
  {
    readMsg += char(SerialBT.read());
    // Serial.println("now is");
    // Serial.println(readMsg);
    // Serial.println("\n");
    delay(2);
  }
}
void loop()
{
  ReceiverBleMessage();
  // Serial.print("this time is:");
  // Serial.print(readMsg);
  if (readMsg == "OPEN")
  {
    int angleValue = OpenParameter;
    dutyCycle = map(angleValue, 0, 180, 5, 32);
    ledcWrite(PWMChannel, dutyCycle);

    delay(200);

    angleValue=ResetParemeter;
    dutyCycle = map(angleValue, 0, 180, 5, 32);
    ledcWrite(PWMChannel, dutyCycle);

    Serial.print("Receiver:");
    Serial.println(readMsg);
  }
  else if (readMsg == "CLOSE")
  {
    int angleValue = CloseParameter;
    dutyCycle = map(angleValue, 0, 180, 5, 32);
    ledcWrite(PWMChannel, dutyCycle);

    delay(200);

    angleValue=ResetParemeter;
    dutyCycle = map(angleValue, 0, 180, 5, 32);
    ledcWrite(PWMChannel, dutyCycle);
    
    Serial.print("Receiver:");
    Serial.println(readMsg);
  }
  readMsg="";
  
}


